<template>
  <div class="material-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.materialId" placeholder="请输入物料编号" clearable />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
      </el-form-item>
      <el-form-item label="材料类型">
        <el-select v-model="searchForm.materialType" placeholder="请选择材料类型" clearable style="width: 100px;">
          <el-option label="金属" value="金属" />
          <el-option label="合金" value="合金" />
          <el-option label="复合材料" value="复合材料" />
          <el-option label="其它" value="其它" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商名称">
        <el-input v-model="searchForm.providerName" placeholder="请输入供应商名称" clearable />
      </el-form-item>
      <el-form-item label="厂址">
        <el-input v-model="searchForm.factoryAddress" placeholder="请输入厂址" clearable />
      </el-form-item>
      <el-form-item label="入库时间">
        <el-date-picker
          v-model="searchForm.storageTimeRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="规格">
        <el-input v-model="searchForm.specification" placeholder="请输入规格" clearable />
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="searchForm.contactPerson" placeholder="请输入联系人" clearable />
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="物料说明">
        <el-input v-model="searchForm.description" placeholder="请输入物料说明" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="showAddDialog = true">添加物料</el-button>
      </el-form-item>
    </el-form>

    <!-- 物料列表 -->
    <el-table :data="materialList" border>
      <el-table-column prop="materialId" label="物料编号" min-width="100" />
      <el-table-column prop="materialName" label="物料名称" min-width="120" />
      <el-table-column prop="materialType" label="材料类型" min-width="100" />
      <el-table-column prop="providerName" label="供应商名称" min-width="120" />
      <el-table-column prop="factoryAddress" label="厂址" min-width="150" />
      <el-table-column prop="storageTime" label="入库时间" min-width="140" :formatter="formatDate" />
      <el-table-column prop="specification" label="规格" min-width="100" />
      <el-table-column prop="contactPerson" label="联系人" min-width="100" />
      <el-table-column prop="phone" label="手机" min-width="120" />
      <el-table-column prop="description" label="物料说明" min-width="150" />
      <el-table-column label="操作" min-width="220">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEditMaterial(row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDeleteMaterial(row.materialId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination

      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 添加物料对话框 -->
    <el-dialog :title="editMaterialId ? '修改物料' : '添加物料'" v-model="showAddDialog">
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="addForm.materialName" />
        </el-form-item>
        <el-form-item label="材料类型" prop="materialType">
          <el-select v-model="addForm.materialType" placeholder="请选择材料类型" style="width: 100%;">
            <el-option label="金属" value="金属" />
            <el-option label="合金" value="合金" />
            <el-option label="复合材料" value="复合材料" />
            <el-option label="其它" value="其它" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商名称" prop="providerName">
          <el-input v-model="addForm.providerName" />
        </el-form-item>
        <el-form-item label="厂址" prop="factoryAddress">
          <el-input v-model="addForm.factoryAddress" />
        </el-form-item>
        <el-form-item label="入库时间" prop="storageTime">
          <el-date-picker v-model="addForm.storageTime" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="addForm.specification" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="addForm.contactPerson" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone" />
        </el-form-item>
        <el-form-item label="物料说明" prop="description">
          <el-input v-model="addForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editMaterialId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const searchForm = reactive({
  materialId: '',
  materialName: '',
  materialType: '',
  providerName: '',
  factoryAddress: '',
  storageTimeRange: [],
  specification: '',
  contactPerson: '',
  phone: '',
  description: ''
})

const addForm = reactive({
  materialName: '',
  materialType: '',
  providerName: '',
  factoryAddress: '',
  storageTime: '',
  specification: '',
  contactPerson: '',
  phone: '',
  description: ''
})

const rules = {
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  materialType: [{ required: true, message: '请选择材料类型', trigger: 'change' }],
  providerName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  factoryAddress: [{ required: true, message: '请输入厂址', trigger: 'blur' }],
  storageTime: [{ required: true, message: '请选择入库时间', trigger: 'change' }],
  specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const materialList = ref([])
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})
const showAddDialog = ref(false)
const editMaterialId = ref(null)
const addFormRef = ref(null)

const handleEditMaterial = (row: any) => {
  Object.assign(addForm, row)
  editMaterialId.value = row.materialId
  showAddDialog.value = true
}

const handleDeleteMaterial = async (materialId: number) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `material/${materialId}`)
    ElMessage.success('删除成功')
    fetchMaterials(1)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

const formatDate = (row: any) => {
  if (!row.storageTime) return ''
  return new Date(row.storageTime).toLocaleDateString('zh-CN')
}

const fetchMaterials = async (pageNum = 1) => {
  try {
    const params = {
      materialId: searchForm.materialId || null,
      materialName: searchForm.materialName || null,
      materialType: searchForm.materialType || null,
      providerName: searchForm.providerName || null,
      factoryAddress: searchForm.factoryAddress || null,
      storageBeginTime: searchForm.storageTimeRange?.[0] || null,
      storageEndTime: searchForm.storageTimeRange?.[1] || null,
      specification: searchForm.specification || null,
      contactPerson: searchForm.contactPerson || null,
      phone: searchForm.phone || null,
      description: searchForm.description || null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `material/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    materialList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    ElMessage.error('获取物料数据失败')
  }
}

const handleSearch = () => {
  fetchMaterials(1)
}

const resetSearch = () => {
  searchForm.materialId = ''
  searchForm.materialName = ''
  searchForm.materialType = ''
  searchForm.providerName = ''
  searchForm.factoryAddress = ''
  searchForm.storageTimeRange = []
  searchForm.specification = ''
  searchForm.contactPerson = ''
  searchForm.phone = ''
  searchForm.description = ''
  fetchMaterials(1)
}

const handlePageChange = (page: number) => {
  fetchMaterials(page)
}

const handleSubmit = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    const url = editMaterialId.value
      ? import.meta.env.VITE_API_URL + 'material/update'
      : import.meta.env.VITE_API_URL + 'material/save'
    
    const params = {
      ...addForm,
      materialId: editMaterialId.value
    }
    
    await axios.post(url, params)
    ElMessage.success(editMaterialId.value ? '修改成功' : '添加成功')
    showAddDialog.value = false
    editMaterialId.value = null
    fetchMaterials(1)
  } catch (e) {
    console.error(e)
    ElMessage.error(editMaterialId.value ? '修改失败' : '添加失败')
  }
}

onMounted(() => {
  fetchMaterials(1)
})
</script>

<style scoped>
@import '@/styles/views.css';
</style>